package utils
{
	import flash.events.Event;

	public class RadioButtons extends Component
	{
		public static const EVENT:String = "event";
		public var checked:uint;
		private var checkButtons:Vector.<Checkbutton>;
		
		public function RadioButtons(text:String, checks:Array, checked:uint)
		{
			if (checks == null || checks.length == 0 || checked > checks.length)
			{
				trace("ERROR: checks == null || checks.length == 0 || active > checks.length");
				return void;
			}
			this.checked = checked;
			addChild(new Label(text));
			checkButtons = new Vector.<Checkbutton>();
			for (var i:int = 0; i < checks.length; i++)
			{
				var check:Checkbutton = new Checkbutton(checks[i]);
				if (i == checked)
				{
					check.setChecked(true);
				}
				checkButtons.push(check);
				check.y = (i+1) * 20;
				check.index = i;
				check.buttonMode = true;
				check.addEventListener(Checkbutton.EVENT, checkClick);
				addChild(check);
			}
		}
		
		protected function checkClick(e:Event):void
		{
			setChecked(Checkbutton(e.target).index);
		}
		
		public function setChecked(index:uint):void
		{
			if (index == checked) return void;
			this.checked = index;
			for (var i:int = 0; i < checkButtons.length; i++)
			{
				if (i == index)
				{
					checkButtons[i].setChecked(true);
				}
				else
				{
					checkButtons[i].setChecked(false);
				}
			}
			dispatchEvent(new Event(RadioButtons.EVENT));
		}
	}
}